//
//  OMMobileTextField.m
//  OMENGO_NEW
//
//  Created by 梁尚嘉 on 2017/4/26.
//  Copyright © 2017年 Kamfat. All rights reserved.
//

#import "OMMobileTextField.h"

@implementation OMMobileTextField
@dynamic om_delegate;

NSInteger i;//定义全局变量
- (instancetype)init
{
    self = [super init];
    [self configure];
    return self;
}

- (void)configure
{
    i = 0;
    [self addTarget:self action:@selector(textFieldDidEditing:) forControlEvents:UIControlEventEditingChanged];
}

- (void)setPhone:(NSString *)phone
{
    NSMutableString *muPhone = [phone mutableCopy];
    [muPhone insertString:@" " atIndex:3];
    [muPhone insertString:@" " atIndex:8];
    self.text = muPhone;
}

- (NSString *)phone
{
    return [self.text stringByReplacingOccurrencesOfString:@" " withString:@""];
}


-(void)textFieldDidEditing:(UITextField *)textField{
    if (textField.text.length > i) {
        if (textField.text.length == 4 || textField.text.length == 9 ) {//输入
            NSMutableString * str = [[NSMutableString alloc ] initWithString:textField.text];
            [str insertString:@" " atIndex:(textField.text.length-1)];
            textField.text = str;
        }if (textField.text.length >= 13 ) {//输入完成
            textField.text = [textField.text substringToIndex:13];
            if (self.om_delegate && [self.om_delegate respondsToSelector:@selector(textField:didFinishedInputAPhone:)]) {
                [self.om_delegate textField:self didFinishedInputAPhone:textField.text];
            }
        }
        i = textField.text.length;

    }else if (textField.text.length < i){//删除
        if (textField.text.length == 4 || textField.text.length == 9) {
            textField.text = [NSString stringWithFormat:@"%@",textField.text];
            textField.text = [textField.text substringToIndex:(textField.text.length-1)];
        }
        i = textField.text.length;
    }

}

@end
